/*
// 商品数据
products = [
  {id, name, price, img},
  ...
]
// 购物车数据
cartItems = [
  {id, count}
]
// 总钱数
all = 1000亿
// dom元素
// 显示钱的位置
allMoneyDiv
// 显示商品列表的位置
productsDiv -> 绑定事件处理买/卖操作
// 显示购物清单的位置
cartItemsDiv
// 渲染
render -> 更改以上三个dom元素里的内容
*/
const all = 1000_0000_0000
const products = text.split('\n').map((line, index) =>{
  // "巨无霸,2,https://neal.fun/spend/images/big-mac.jpg"
  const [name, price, img] = line.split(',')
  return {id: index, name, price: +price, img}
})
// console.log(products)
const key = 'billgates_app'
function save() {
  localStorage.setItem(key, JSON.stringify(cartItems))
}
function load() {
  return JSON.parse(localStorage.getItem(key)) || []
}
const cartItems = load()

function $(selector) {
  return document.querySelector(selector)
}
// 通过id获得商品
function getProductById(id) { return products[id] }
// 计算购物清单的总价
function getTotalMoney() {
  return cartItems.reduce((s, item) => {
    const p = getProductById(item.id)
    return s + p.price * item.count
  }, 0)
}
// 计算剩余的钱
function getCurrentMoney() {
  return all - getTotalMoney()
}
// 通过id返回购物车里的内容 - [索引, item]
function getCartItemById(id) {
  const index = cartItems
    .findIndex(item => item.id === id)
  return [index, cartItems[index]]
}
function buy(id) {
  const p = getProductById(id)
  if (p.price <= getCurrentMoney()) { // 手里的钱够消费吗？
    const [,item] = getCartItemById(id)
    if (item) {
      // 给已有购物车item数量+1
      item.count += 1
    } else {
      // 添加一个商品进入购物车
      cartItems.push({id: p.id, count: 1})
    }
  }
  return cartItems
}
function sell(id) {
  const [index, item] = getCartItemById(id)
  if (item) {
    item.count -= 1
    item.count === 0 && cartItems.splice(index, 1)
  }
  return cartItems
}
// --- 渲染相关 ---
// 渲染商品列表
function renderProductList() {
  productsDiv.innerHTML = products.map(p => {
    const [,item] = getCartItemById(p.id)
    return `<li>
    <div class="item">
      <img src="${p.img}" alt="" />
      <div class="name">${p.name}</div>
      <div class="cost">$${p.price}</div>
      <div class="controls">
        <button
          class="sell" ${item ? '' : 'disabled'}
          data-id="${p.id}"
        >卖</button>
        <input type="text" class="input" readonly
          value="${(item && item.count) || 0}"/>
        <button class="buy" data-id="${p.id}">买</button>
      </div>
    </div>
  </li>`
  }).join('')
}

function renderCartItems() {
  if (cartItems.length === 0) {
    cartItemsDiv.style.display = 'none'
  } else {
    cartItemsDiv.style.display = ''
    // 购物车列表
    $('#cartItems').innerHTML = cartItems.map(item => {
      const p = getProductById(item.id)
      return `<div class="spree-items">
      <div class="spree-item-name">${p.name}</div>
      <div class="spree-item-amount">x${item.count}</div>
      <div class="spree-item-cost">$${item.count*p.price}</div>
    </div>`
    }).join('')
    // 总花费
    cartItemsDiv.querySelector('.spree-total-money')
      .innerText = '$'+(getTotalMoney()).toLocaleString()
  }
}
// 1000 - 900
let rollMoney = all // 正在滚动的钱
let timer = 0
function getRollingStepCount(diff) { // 计算一共需要多少步
  diff = Math.abs(diff)
  switch(true) {
    case diff > 100_000: return 200;
    case diff > 50_000: return 150;
    case diff > 30_000: return 120;
    case diff > 5000: return 100;
    case diff > 1000: return 50;
    case diff > 100: return 20;
    case diff > 0: return 15;
    default: return 0;
  }
}
function rollingMoney(start, end) {
  clearInterval(timer)
  let stepCount = getRollingStepCount(end-start) // 经过多少步才滚动完
  console.log(stepCount)
  let step = 0 // 当前第几步
  rollMoney = start
  timer = setInterval(() => {
    step += 1
    if (step > stepCount) {
      clearInterval(timer)
      timer = 0
      return
    }
    const r = step/stepCount
    const percent = r * (2-r) // 19 36 51 ... 99 100
    rollMoney = Math.round((end - start)*percent + start)
    allMoneyDiv.innerText = '$' + rollMoney.toLocaleString()
  }, 1000/60)
}
function renderCurrentMoney() {
  // rollingMoney(rollMoney, getCurrentMoney())
  allMoneyDiv.innerText = '$'+getCurrentMoney().toLocaleString()
}

function render() {
  renderProductList()
  renderCartItems()
  renderCurrentMoney()
}

const allMoneyDiv = $('.money')
const productsDiv = $('.list')
const cartItemsDiv = $('.spree-wrapper')

productsDiv.onclick = function(e) {
  if (e.target.tagName === 'BUTTON') {
    const id = +e.target.getAttribute('data-id')
    if (e.target.className === 'buy') {
      buy(id)
    } else {
      sell(id)
    }
    render()
    save()
  }
}

render()